import axios from 'axios'
import store from '@/store'

import { customHistory } from './history'
import { logout } from '@/store/actions'
import { message } from 'antd'


const http = axios.create({
  // baseURL: 'http://geek.itheima.net/v1_0'
  baseURL: process.env.REACT_APP_URL
})

// 请求拦截器
http.interceptors.request.use(config => {
  // 获取token
  const { login: token } = store.getState()

  // 除了登录请求外，其他请求统一添加 token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }

  return config
})


// 简化返回数据
http.interceptors.response.use((res) => {
  return res.data
}, (error) => {
  if (error.response.status === 401) {
    message.error(error.response.data?.message, 1.5, () => {
      // 删除token
      store.dispatch(logout())
      // 跳转到登录页，并携带当前要访问的页面，这样，登录后可以继续返回该页面
      // customHistory.push('/login', {
      //   from: customHistory.location.pathname
      // })
      customHistory.push({ pathname: '/login', state: { from: customHistory.location.pathname } })
    })
  }
  return Promise.reject(error)
})

export { http }